import worldCities from "./world.json";

export const getCityName = (name: string) => {
  return worldCities.find((city) => city.name === name)?.zh || name;
};

export const getCityNameByAlias = (name: string) => {
  return worldCities.find((city) => city.alias === name)?.zh || name;
}

// 根据等级获取消耗比例
const getBili = (tType: number) => {
  if (tType === 3) {
    return 2;
  } else if (tType === 4) {
    return 2;
  } else if (tType === 5) {
    return 3;
  } else if (tType === 6) {
    return 4;
  } else if (tType === 7) {
    return 5;
  } else if (tType === 8) {
    return 5;
  }
  return 3;
};

// 获取每次计算的价格
const getTotalPrice = (price1, bili1, price2, bili2) => {
  const result1 = price1 * bili1;
  const result2 = price2 * bili2;
  return result1 + result2;
};

// 根据返还率计算返还数
const getReturnValue = (count: number, returnVal: number) => {
  if (returnVal === undefined) {
    return 0;
  }
  return Math.round(count * returnVal);
};

// 获取单次创建的价格和返还值
const getSingleCreate = (max: number, returnVal: number) => {
  // 获取返还值
  const singleReturnCount = getReturnValue(max, returnVal);
  return singleReturnCount;
};

/**
 * 制造价格
 * @param tType 等级
 * @param item1Price 材料1价格
 * @param item2Price 材料2价格
 * @param item1Count 材料1数量
 * @param item2Count 材料2数量
 * @param createPrice 制造价格
 * @param shuilv 税率
 * @param sellPrice 出售价格
 * @param returnVal 返还率
 * @returns
 */
export const makePrice = ({
  tType,
  item1Price,
  item2Price,
  item1Count,
  createPrice,
  shuilv,
  sellPrice,
  returnVal,
}) => {
  const bili = getBili(tType);
  // 获取能做的最大数
  let result1 = Math.floor(item1Count / bili);
  // 最多能做的数量
  let max = result1;
  let totalCreateCount = result1;
  const cailiao1Chenben = result1 * bili * item1Price;
  const cailiao2Chenben = result1 * item2Price;
  while (max >= bili) {
    const singleReturnCount = getSingleCreate(max, returnVal);
    totalCreateCount += singleReturnCount;
    max = singleReturnCount;
  }
  const totalCreateChenben = totalCreateCount * createPrice;
  // 总材料成本+总制造成本
  const totalChenben = totalCreateChenben + cailiao1Chenben + cailiao2Chenben;
  // 总税费
  const totalShui = Math.round(((sellPrice * shuilv) / 100) * totalCreateCount);
  // 总销售额
  const totalMarketPrice = sellPrice * totalCreateCount;
  // 总利润
  const lirun = Math.round(totalMarketPrice - totalChenben - totalShui);
  return {
    totalCreateCount,
    totalCreateChenben,
    totalChenben,
    totalShui,
    totalMarketPrice,
    lirun,
  };
};

// 获取是否是基础材料
const getBaseCailiao = (caoliaoId: string) => {
  return (
    caoliaoId === "FIBER" ||
    caoliaoId === "WOOD" ||
    caoliaoId === "ORE" ||
    caoliaoId === "STONE" ||
    caoliaoId === "HIDE"
  );
};

// 获取是否是制造品
const getMakeItem = (caoliaoId: string) => {
  return (
    caoliaoId === "CLOTH" ||
    caoliaoId === "PLANKS" ||
    caoliaoId === "METALBAR" ||
    caoliaoId === "STONEBLOCK" ||
    caoliaoId === "LEATHER"
  );
};

// 获取材料关联关系
const getConectionByCailiao = (caoliaoId: string) => {
  if (caoliaoId === "FIBER") {
    return "CLOTH";
  } else if (caoliaoId === "WOOD") {
    return "PLANKS";
  } else if (caoliaoId === "ORE") {
    return "METALBAR";
  } else if (caoliaoId === "STONE") {
    return "STONEBLOCK";
  } else if (caoliaoId === "HIDE") {
    return "LEATHER";
  }
  return "";
};

// 获取材料关联关系
const getConectionByMakeItem = (caoliaoId: string) => {
  if (caoliaoId === "CLOTH") {
    return "FIBER";
  } else if (caoliaoId === "PLANKS") {
    return "WOOD";
  } else if (caoliaoId === "METALBAR") {
    return "ORE";
  } else if (caoliaoId === "STONEBLOCK") {
    return "STONE";
  } else if (caoliaoId === "LEATHER") {
    return "HIDE";
  }
  return "";
};

// 根据id获取材料名称
const getCailiaoName = (id: string) => {
  const cailiaoId = id.split("@")[0].split("_")[1];
  const tType = id.split("_")[0];
  let levelName = id.split("@")?.[1];
  let level = "0";
  if (levelName) {
    level = levelName.slice(-1);
  }
  return {
    cailiaoId,
    tType: Number(tType.slice(-1)),
    level: Number(level),
  };
};

/**
 * 获取制造材料数据
 */
export const getMakeData = (data: any) => {
  const allBaseCailiao = data.filter((item: any) => {
    const { cailiaoId } = getCailiaoName(item.id);
    if (!getBaseCailiao(cailiaoId)) {
      return false;
    }
    return true;
  });
  console.log("allBaseCailiao: ", allBaseCailiao);

  const allMakeItem = data.filter((item: any) => {
    const { cailiaoId } = getCailiaoName(item.id);
    if (!getMakeItem(cailiaoId)) {
      return false;
    }
    return true;
  });
  let allMakeData = {};
  allMakeItem.forEach((item) => {
    const { cailiaoId, tType, level } = getCailiaoName(item.id);
    const fullMakeId = `T${tType}_${cailiaoId}${
      level ? `_LEVEL${level}@${level}` : ""
    }`;
    const conectionCailiao = getConectionByMakeItem(cailiaoId);
    const fullCailiaoId = `T${tType}_${conectionCailiao}${
      level ? `_LEVEL${level}@${level}` : ""
    }`;

    const fullDiJIMakeId = `T${tType - 1}_${cailiaoId}${
      tType > 4 && level ? `_LEVEL${level}@${level}` : ""
    }`;
    allMakeData[fullMakeId] = {
      fullMakeData: item,
      fullCailiaoData: allBaseCailiao.find((item: any) => {
        return item.id === fullCailiaoId;
      }),
      fullDiJIMakeData: allMakeItem.find((item: any) => {
        return item.id === fullDiJIMakeId;
      }),
    };
  });
  console.log("allMakeData", allMakeData);
  Object.keys(allMakeData).forEach((key) => {
    const { fullMakeData, fullCailiaoData, fullDiJIMakeData } =
      allMakeData[key];
    const fullMakeDataCitiys = fullMakeData?.citys;
    const fullCailiaoDataCitys = fullCailiaoData?.citys;
    console.log("fullCailiaoDataCitys: ", fullCailiaoDataCitys);
    const fullDiJIMakeDataCitys = fullDiJIMakeData?.citys;

    if (!fullCailiaoDataCitys || !fullDiJIMakeDataCitys || !fullMakeDataCitiys)
      return;

    const minSellPrice1 = Math.min(
      ...fullMakeDataCitiys.map((item) =>
        item.sell_price_min === 0 ? 999999999 : item.sell_price_min
      )
    );
    const maxBuyPrice1 = Math.max(
      ...fullMakeDataCitiys.map((item) =>
        item.buy_price_max === 0 ? 0 : item.buy_price_max
      )
    );
    const minSellPrice2 = Math.min(
      ...fullCailiaoDataCitys.map((item) =>
        item.sell_price_min === 0 ? 999999999 : item.sell_price_min
      )
    );
    const maxBuyPrice2 = Math.max(
      ...fullCailiaoDataCitys.map((item) =>
        item.buy_price_max === 0 ? 0 : item.buy_price_max
      )
    );
    const minSellPrice3 = Math.min(
      ...fullDiJIMakeDataCitys.map((item) =>
        item.sell_price_min === 0 ? 999999999 : item.sell_price_min
      )
    );
    const maxBuyPrice3 = Math.max(
      ...fullDiJIMakeDataCitys.map((item) =>
        item.buy_price_max === 0 ? 0 : item.buy_price_max
      )
    );
    const minSellPriceCity1 = fullMakeDataCitiys.find(
      (item) => item.sell_price_min === minSellPrice1
    );
    const maxBuyPriceCity1 = fullMakeDataCitiys.find(
      (item) => item.buy_price_max === maxBuyPrice1
    );
    const minSellPriceCity2 = fullCailiaoDataCitys.find(
      (item) => item.sell_price_min === minSellPrice2
    );
    const maxBuyPriceCity2 = fullCailiaoDataCitys.find(
      (item) => item.buy_price_max === maxBuyPrice2
    );
    const minSellPriceCity3 = fullDiJIMakeDataCitys.find(
      (item) => item.sell_price_min === minSellPrice3
    );
    const maxBuyPriceCity3 = fullDiJIMakeDataCitys.find(
      (item) => item.buy_price_max === maxBuyPrice3
    );
    fullMakeData.minSellCity = minSellPriceCity1;
    fullMakeData.maxBuyCity = maxBuyPriceCity1;
    fullCailiaoData.minSellCity = minSellPriceCity2;
    fullCailiaoData.maxBuyCity = maxBuyPriceCity2;
    fullDiJIMakeData.minSellCity = minSellPriceCity3;
    fullDiJIMakeData.maxBuyCity = maxBuyPriceCity3;
    // delete fullMakeData.citys;
    // delete fullCailiaoData.citys;
    // delete fullDiJIMakeData.citys;
  });

  return allMakeData;
};

export const getCreatePriceByTTypeAndLevel = (tType, level) => {
  if (tType === 3) {
    const levelPrice = [5, 10, 30, 60, 100];
    return levelPrice[level - 1];
  } else if (tType === 4) {
    const levelPrice = [10, 20, 60, 120, 200];
    return levelPrice[level - 1];
  } else if (tType === 5) {
    const levelPrice = [20, 40, 120, 240, 400];
    return levelPrice[level - 1];
  } else if (tType === 6) {
    const levelPrice = [40, 80, 240, 480, 800];
    return levelPrice[level - 1];
  }
};

/**
 * 获取是否有制造利润
 *
 */
export const getMakeLirun = (
  data: any,
  cailiao1Count: number,
  shuilv: number,
  returnVal: number
) => {
  const allMakeData = getMakeData(data);
  let result: any = [];
  Object.keys(allMakeData).forEach((key) => {
    const element = allMakeData[key];
    const { fullMakeData, fullCailiaoData, fullDiJIMakeData } = element;
    const { tType, level } = getCailiaoName(fullMakeData.id);
    if (
      !fullMakeData?.maxBuyCity ||
      !fullCailiaoData?.minSellCity ||
      !fullDiJIMakeData?.minSellCity
    )
      return;
    console.log("fullMakeData: ", fullMakeData.minSellCity);
    console.log("fullCailiaoData: ", fullCailiaoData.minSellCity);
    const {
      totalCreateCount,
      totalCreateChenben,
      totalChenben,
      totalShui,
      totalMarketPrice,
      lirun,
    } = makePrice({
      tType,
      item1Price: fullCailiaoData.minSellCity.sell_price_min,
      item2Price: fullDiJIMakeData.minSellCity.sell_price_min,
      item1Count: cailiao1Count,
      createPrice: getCreatePriceByTTypeAndLevel(tType, level),
      shuilv: shuilv,
      sellPrice: fullMakeData.maxBuyCity.buy_price_max,
      returnVal: returnVal,
    });
    console.log("lirun: ", lirun);

    if (lirun > 50 * 10000) {
      result.push({
        tType,
        level,
        totalCreateCount,
        totalCreateChenben: formatNumber(totalCreateChenben),
        totalChenben: formatNumber(totalChenben),
        totalShui: formatNumber(totalShui),
        totalMarketPrice: formatNumber(totalMarketPrice),
        lirun: formatNumber(lirun),
        fullMakeData,
        fullCailiaoData,
        fullDiJIMakeData,
      });
    }
  });

  return result;
};

// 格式化数字为K或M
const formatNumber = (num: number): string => {
  if (num >= 1000000) {
    return `${(num / 1000000).toFixed(2)}M`;
  } else if (num >= 1000) {
    return `${(num / 1000).toFixed(2)}K`;
  }
  return num.toString();
};

// 根据结果输出路径
export const getOutputInfo = (data: any) => {
  console.log('data: ', data);
  const lirun = formatNumber(data.lirun);
  const makeId = data.fullMakeData.id;
  const makeName = data.fullMakeData.name;
  const makeCity = getCityName(data.fullMakeData.maxBuyCity.city);
  const makePrice = data.fullMakeData.maxBuyCity.buy_price_max;
  const cailiao1Id = data.fullCailiaoData.id;
  const cailiao1Name = data.fullCailiaoData.name;
  const cailiao1City = getCityName(data.fullCailiaoData.minSellCity.city);
  const cailiao1Price = data.fullCailiaoData.minSellCity.sell_price_min;
  const cailiao2Id = data.fullDiJIMakeData.id;
  const cailiao2Name = data.fullDiJIMakeData.name;
  const cailiao2City = getCityName(data.fullDiJIMakeData.minSellCity.city);
  const cailiao2Price = data.fullDiJIMakeData.minSellCity.sell_price_min;
  const totalCreateChenben = formatNumber(data.totalCreateChenben);
  const totalChenben = formatNumber(data.totalChenben);
  const totalShui = formatNumber(data.totalShui);
  const totalMarketPrice = formatNumber(data.totalMarketPrice);
  const totalCreateCount = data.totalCreateCount;
  return `利润${lirun}，从${cailiao1City}以${cailiao1Price}单价购买${cailiao1Name}[${cailiao1Id}],
  从${cailiao2City}以${cailiao2Price}单价购买${cailiao2Name}[${cailiao2Id}],
  在${makeCity}以${makePrice}单价售卖${makeName}[${makeId}],售卖数量${totalCreateCount},
  制造成本${totalCreateChenben},总成本${totalChenben},总税收${totalShui},
  总市场价${totalMarketPrice}`;
};
